#pragma once

#include "obj_pointer.h"
#include <vector>


OPEN_JLIB_NS


struct ObjCache {

  void cache (Obj* obj) noexcept {
    debug_assert(obj);
    _pool.emplace_back(obj);
  }
  
  void flush () {
    _pool.clear();
  }
  
  u64 count () const noexcept {
    return _pool.size();
  }


  static void gcache (Obj* obj) noexcept {
    __global.cache(obj);
  }

  static void gflush () {
    __global.flush();
  }

  static u64 gcount () noexcept {
    return __global.count();
  }


  template<typename Type, typename... Args1, typename... Args2>
  static Type* create (Args1... args1, Args2... args2) {
    static_assert(std::is_base_of<Obj, Type>::value, "");
    auto obj = new Type(args1...);
    if (!obj->init(args2...)) {
      obj->release();
      return nullptr;
    }
    gcache(obj);
    return obj;
  }
  

private:
  std::vector<Ptr<Obj>> _pool;

  static ObjCache __global;
};


CLOSE_JLIB_NS
